﻿using Microsoft.AspNetCore.Mvc;
using ProjectScheduling_web.dao;
using ProjectScheduling_web.model;
using ProjectScheduling_web.model.Enums;

namespace ProjectScheduling_web.Controllers.U
{
    public class ProductController : BController
    {
        private readonly static ProductDao @base = ProductDao.Base;
        [HttpGet]
        public IActionResult Search(int page = 1, int row = 10, int categoryId = 0, string key = "")
        => Success(@base.Search(page, row, categoryId, key));
        [HttpGet]
        public IActionResult Find(int id)
        => Success(@base.Find(id));
        [HttpPost]
        public IActionResult Update([FromBody] Product item)
        {
            if (item == null)
                return Fail("产品不能为空");
            if (string.IsNullOrEmpty(item.Name))
                return Fail("产品名称不能为空");
            if (item.CatetoryId <= 0)
                return Fail("产品类别不能为空");
            var category = DictionaryDataDao.Base.Find(z => z.Category == EnumDictionaryCategory.产品类型 && z.Value == item.CatetoryId);
            if (category == null)
                return Fail("产品类别不存在");
            item.CategoryName = category.Name;
            if (item.Money <= 0)
                return Fail("产品价格不能为空");
            if (@base.Exists(it => it.Code == item.Code && it.Id != item.Id))
                return Fail("产品编码不能重复");
            if (item.Id > 0)
            {
                if (@base.Update(item, it => new { it.Name, it.CatetoryId, it.CategoryName, it.Spec, it.Money, it.Code,it.Unit }) > 0)
                    return Success("修改成功");
                else
                    return Fail("修改失败，产品不存在或数据未修改");
            }
            else
            {
                if (CurrUser != null)
                {
                    item.CreaterId = CurrUser.Id;
                    item.CreaterName = CurrUser.Name;
                }
                item.CreateTime = DateTime.Now;
                if (@base.Add(item) > 0)
                    return Success("添加成功");
                else
                    return Fail("添加失败，产品已存在或数据未修改");
            }
        }
        [HttpGet]
        public IActionResult Remove(int id)
        {
            if (@base.Delete(id) > 0)
                return Success("删除成功");
            else
                return Fail("删除失败，产品不存在或数据未修改");
        }
    }
}
